package com.ruc.dbiir.rest.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruc.dbiir.rest.utils.Config;
import com.ruc.dbiir.rest.utils.ParseUtil;
import com.ruc.dbiir.rest.utils.ReadFileUtil;
import com.ruc.dbiir.rest.utils.RemoteExecuteCommand;
import com.ruc.dbiir.rest.utils.SSHWindows;

/**
 * 前端和数据生成器/数据库不在同一个服务器上的情况，需要远程执行shell脚本
* author：mark   
* createTime：Nov 11, 2019 10:41:15 AM   
* @version
 */

@Controller
@RequestMapping(value = "/highEchart2")
public class HignChartsController2 {



	/**
	 * 向生成器发送请求进行数据生成
	 * author：mark   
	 * createTime：Sep 7, 2018 4:55:58 PM
	 * @param username
	 * @param passwd
	 * @param nodetype
	 * @param edgetype
	 * @param querysize
	 * @param graphsize
	 * @return
	 */

	//	username:data.field.username, passwd:data.field.passwd, 
	//	nodetype:data.field.nodetype,edgetype:data.field.edgetype,
	//	querysize:data.field.querySize,graphsize:data.field.graphSize,
	//	graphLayer:data.field.graphLayer,graphNum:data.field.graphNum

	@RequestMapping(value = "/startGen")
	@ResponseBody
	public Object urlcon( @RequestParam(value = "username") String username,  @RequestParam(value = "passwd") String passwd,
			@RequestParam(value = "nodetype") String nodetype,@RequestParam(value = "edgetype") String edgetype,
			@RequestParam(value = "querySize") String querySize,@RequestParam(value = "graphSize") String graphSize,
			@RequestParam(value = "graphLayer") String graphLayer,@RequestParam(value = "graphNum") String graphNum) {

		HttpURLConnection urlCon = null;
		StringBuilder result = null;
		try {
			String urls = Config.PYSERVER_ADDR+"/startGen?"+username+"&"+passwd
					+"&"+nodetype+"&"+edgetype+"&"+querySize+"&"+graphSize+"&"+graphLayer+"&"+graphNum;
			System.out.println(urls);
			URL url = new URL(urls);
			urlCon = (HttpURLConnection)url.openConnection();
			urlCon.setConnectTimeout(300 * 1000);
			urlCon.setReadTimeout(300 * 1000);
			urlCon.setRequestMethod("GET");
			InputStream is =  urlCon.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String inputLine=null;
			result = new StringBuilder("");
			if((inputLine = br.readLine()) != null){
				System.out.println(inputLine);
				result.append(inputLine+"<br>");
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(result);
		urlCon.disconnect();
		return ParseUtil.toObject(result.toString());
	}


	/**
	 * 获取内容列表
	 * author：mark   
	 * createTime：Sep 7, 2018 4:56:20 PM
	 * @return
	 */
	@RequestMapping(value = "/getContentList")
	@ResponseBody
	public static Object getContentList() {
		
		RemoteExecuteCommand rec=new RemoteExecuteCommand(Config.IP, Config.user, Config.passwd);  
        //执行命令  
//        System.out.println(rec.execute("du /home/ubuntu/graph/GenGraph"));

		String command = "sh " + Config.CMD_ADDR_LIST;
		String result = rec.execute(command);
		List<String> processList = new ArrayList<String>(); 
		
		System.out.println(result);
		String [] rearr = result.split("\n");
		for (int i = 0; i < rearr.length-1; i++) {
			System.out.println(rearr[i].split("./")[0].trim()+"&"+rearr[i].split("./")[1]);
			processList.add(rearr[i].split("./")[0].trim()+"&"+rearr[i].split("./")[1]); 
		}
		
		
		
		
//		final List<String> processList = new ArrayList<String>(); 
//
//		try {  
//			final Process process = Runtime.getRuntime().exec(command);  	
//			BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));  
//			String line = "";  
//			while ((line = input.readLine()) != null) {  
//				line = line+"/suf";
//				System.out.println(line);
//				processList.add(line.split("/")[0]+"&"+line.split("/")[1]); 
//			}  
//			input.close(); 
//		} catch (IOException e) {  
//			e.printStackTrace();  
//		}  
//		for (String line : processList) {  
//			System.out.println(line);  
//		}  
		return processList;
		
//				return ParseUtil.toObject("sss");
	}


	/**
	 * 自动化进行测试
	 * author：mark   
	 * createTime：Sep 7, 2018 4:56:20 PM
	 * @return
	 */
	@RequestMapping(value = "/testPerformance")
	@ResponseBody
	public Object testPerformance(@RequestParam(value = "graphName") String graphName,@RequestParam(value = "dbPath") String dbPath) {

	    System.out.println(graphName+"dddd"+dbPath);
		//		String shpath="/Users/mark/program/proWorkspace/pyCharmSrc/GenGraph/result/Execute_Command.sh";//.sh文件的绝对路径
		String command = "sh " + Config.RESULT_PATH+graphName+"/Execute_Command.sh "+dbPath;

		final List<String> processList = new ArrayList<String>(); 
		try {  

			final Process process = Runtime.getRuntime().exec(command);  	
			BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));  
			String line = "";  
			while ((line = input.readLine()) != null) {  
				processList.add(line); 
			}  
			input.close(); 

		} catch (IOException e) {  
			e.printStackTrace();  
		}  
		for (String line : processList) {  
			System.out.println(line);  
		}  
		return processList;
		//		return ParseUtil.toObject("sss");
	}
	
	/**
	 * 自动化进行测试Oracle
	 * author：mark   
	 * createTime：Sep 7, 2018 4:56:20 PM
	 * @return
	 */
	@RequestMapping(value = "/testPerformanceOracle")
	@ResponseBody
	public static Object testPerformanceOracle() {

//		2019-10-21 16:29:21.356000
//		2019-10-21 16:29:21.361000
//		2019-10-21 16:29:21.387000
//		2019-10-21 16:29:21.410000
//		2019-10-21 16:29:21.480000
		List<String> timelist = SSHWindows.executeWinCmd();
		List<Integer> tarr = new ArrayList<>();
		List<Integer> tre = new ArrayList<>();
		
		for(int i=0;i<timelist.size();i++) {
			String timestr = timelist.get(i);
			String arr[] = timestr.split(":");
			System.out.println(arr[0]+"|"+arr[1]+"|"+arr[2]);
			int min = Integer.parseInt(arr[1]);
			String ssString = arr[2].replace('.', '-');
			String ss[] = ssString.split("-");
//			System.out.println(ss[0]+"--"+ss[1]);
			int sec = Integer.parseInt(ss[0]);
			int millsec = Integer.parseInt(ss[1]);
//			
			int ts = min*60*1000+sec*1000+millsec/1000;
			tarr.add(ts);
		}
//		
		for (int i = 0; i < tarr.size()-1; i++) {
			tre.add(tarr.get(i+1)-tarr.get(i));
			System.out.println(tre.get(i));
		}
		
		return tre;
	}
	
	

	/**
	 * 添加数据库
	 * author：mark   
	 * createTime：Sep 7, 2018 4:56:20 PM
	 * @return
	 */
	@RequestMapping(value = "/addDatabase")
	@ResponseBody
	public Object addDatabase(@RequestParam(value = "dbName") String dbName,@RequestParam(value = "dbType") String dbType,
			@RequestParam(value = "dbPath") String dbPath) {
		//		System.out.println("adddddddddd----------dbdb");
		String path = Config.RESULT_PATH+"dbCollect.csv";
		String content = dbName+","+dbType+","+dbPath+"\n";
		boolean append = true;
		ReadFileUtil.directFileWriter(path, content, append);
		return ParseUtil.toObject("success");
	}

	/**
	 * 获取数据库
	 * author：mark   
	 * createTime：Sep 7, 2018 4:56:20 PM
	 * @return
	 */
	@RequestMapping(value = "/getDatabase")
	@ResponseBody
	public Object getDatabase() {
		String path = Config.RESULT_PATH+"dbCollect.csv";
		List<String> dbList = ReadFileUtil.readFile(path);
		for (int i = 0; i < dbList.size(); i++) {
			System.out.println(dbList.get(i));
		}
		return dbList;
	}


	/**
	 * 获取一个可用的数据库用以倒入数据并展示
	 * author：mark   
	 * createTime：Oct 14, 2019 6:59:32 PM
	 * @return
	 */
	public static String getAvaliableDBPath() {
//		String path = Config.RESULT_PATH+"dbCollect.csv";
//		List<String> dbList = ReadFileUtil.readFile(path);
//		String dbStr = dbList.get(0);
//		String arr[] = dbStr.split(",");
//		String dbPath = arr[2];
		
		return "/home/ubuntu/graph/neo4j-community-3.4.6";
	}

	@RequestMapping(value = "/getDatabaseList")
	@ResponseBody
	public Object getDatabaseList() {
		String path = Config.RESULT_PATH+"dbCollect.csv";
		JSONArray  jsonArray = new JSONArray();
		JSONObject jObj = new JSONObject();
		List<String> dbList = ReadFileUtil.readFile(path);
		for (int i = 0; i < dbList.size(); i++) {
			System.out.println(dbList.get(i));
			String dbStr = dbList.get(i);
			String arr[] = dbStr.split(",");
			JSONObject jObject = new JSONObject();
			System.out.println(arr[0]+"|"+arr[1]);
			jObject.put("dbName", arr[0]);
			jObject.put("dbType", arr[1]);
			jObject.put("dbPath", arr[2]);
			jsonArray.add(jObject);
		}
		jObj.put("data", jsonArray);
		jObj.put("code", 0);
		jObj.put("msg", "");
		jObj.put("count", 1000);
		return jObj;
	}

//	public static Object getDatabaseList1() {
//		String path = Config.RESULT_PATH+"dbCollect.csv";
//		JSONArray  jsonArray = new JSONArray();
//		JSONObject jObj = new JSONObject();
//		List<String> dbList = ReadFileUtil.readFile(path);
//		for (int i = 0; i < dbList.size(); i++) {
//			System.out.println(dbList.get(i));
//			String dbStr = dbList.get(i);
//			String arr[] = dbStr.split(",");
//			JSONObject jObject = new JSONObject();
//			jObject.put("dbName", arr[0]);
//			jObject.put("dbPath", arr[1]);
//			jsonArray.add(jObject);
//			
//		}
//		jObj.put("data", jsonArray);
//		return jObj;
//	}

	
	/**
	 * 获取图数据
	 * author：mark   
	 * @return
	 */
	@RequestMapping(value = "/getGraph")
	@ResponseBody
	public static  Object getGraph(@RequestParam(value = "graphName") String graphName) {

//		String shpath="/Users/mark/program/proWorkspace/pyCharmSrc/GenGraph/result/Execute_Command.sh";//.sh文件的绝对路径
		//		String command = "sh /Users/mark/Desktop/tmp/test.sh /Users/mark/Documents/MasterLife/GraphDB/neo4j-community-3.4.6";
//		/Users/mark/program/proWorkspace/pyCharmSrc/GenGraph/result/result_2019101022310
		String path = "/home/ubuntu/graph/neo4j-community-3.4.6";
		String command = "sh " + Config.RESULT_PATH+graphName+"/getSub.sh "+path;
		System.out.println(command);
		
		RemoteExecuteCommand rec=new RemoteExecuteCommand(Config.IP, Config.user, Config.passwd);  
		String result = rec.execute("sh /home/ubuntu/graph/GenGraph/result/result_20191110173619/getSub.sh /home/ubuntu/graph/neo4j-community-3.4.6");
		System.out.println(result);
		
//		final List<String> processList = new ArrayList<String>(); 
//
//		try {  
//			final Process process = Runtime.getRuntime().exec(command);  	
//			BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));  
//			String line = "";  
//			while ((line = input.readLine()) != null) {  
//				processList.add(line); 
//			}  
//			input.close(); 
//
//		} catch (IOException e) {  
//			e.printStackTrace();  
//		}  
//		
//		List<String> list = new ArrayList<>();
//		for (String line : processList) {  
//			System.out.println(line);
//			if (line.length()>0) {
//				if (line.charAt(0)=='\"'&&line.charAt(1)!='S'&&line.charAt(1)!='E') {
////					JSONObject jobj1 = JSONObject.parseObject(arr[0]);
////					System.out.println(line);
//					String arr[] = line.split("\"");
//					String node1 = arr[1]+","+arr[3]+","+arr[5];
//					System.out.println(node1);
//					String node2 = arr[7]+","+arr[9]+","+arr[11];
//					System.out.println(node2);
//					String rel = arr[13]+","+arr[15]+","+arr[17];
//					System.out.println(rel);
//					String reString = node1+"&"+node2+"&"+rel;
//					list.add(reString);
//				}
//			}
//		}  
//		return list;
				return ParseUtil.toObject("sss");
	}


	public static void main(String[] args) {
//		getGraph();
		//		addDatabase();///////////////////////////
		//		getDatabase2();
//		getDatabaseList1();
//		System.out.println((3.67*3+3.67*3+3.67*1+4*3+3.67*3+4*4+4*4+3.67*3+3.67*3+4*3+3.67*2+2.67*3)/35);
//		testPerformanceOracle();
//		getContentList();
		getGraph("result_20191110173619");
	}


}
